var piStore;
var piGrid;
var piWindow;
var ctDesignTypeXmlLoader = new i18nMessage('../../servlet/CodeTableServlet?name=CtDesignType');
var ctCostumeCategoryXmlLoader = new i18nMessage('../../servlet/CodeTableServlet?name=CtCostumeCategory');
var ctMachineTypeXmlLoader = new i18nMessage('../../servlet/CodeTableServlet?name=CtMachineType');
var ctCollarTypeXmlLoader = new i18nMessage('../../servlet/CodeTableServlet?name=CtCollarType');
var ctVersionXmlLoader = new i18nMessage('../../servlet/CodeTableServlet?name=CtVersion');
var ctProductIdentificationStyleXmlLoader = new i18nMessage('../../servlet/CodeTableServlet?name=CtProductIdentificationStyle');
var ctSeasonNumberXmlLoader = new i18nMessage('../../servlet/CodeTableServlet?name=CtSeasonNumber');
var ctProductFamilyXmlLoader = new i18nMessage('../../servlet/CodeTableServlet?name=CtProductFamily');
var ctVersion = new i18nMessage('../../servlet/CodeTableServlet?name=CtVersion');
var ctProductFamily = new i18nMessage('../../servlet/CodeTableServlet?name=CtProductFamily');
var ctDesignType = new i18nMessage('../../servlet/CodeTableServlet?name=CtDesignType');
var selectedRecords = new Array();
var selectedIds = new Array();
function locateProductIdentification(rowIndex){
	selectedProductIdentification = piStore.getAt(rowIndex).data;
}
var selectPiCallback;
var selectProductIdentification = function(selectProductIdentificationCallback, ctCollarType, ctSeasonNumber, reference, action){
	selectPiCallback = selectProductIdentificationCallback;
	var piUrl;
	if(action=="1")
		piUrl = '../../servlet/ProductIdentificationServlet?action=104';
	else if(action=="2"){
		piUrl = '../../servlet/ProductIdentificationServlet?action=103';
	}else{
		piUrl = '../../servlet/ProductIdentificationServlet?action=100';
	}
	if(ctCollarType){
		piUrl += '&ctCollarType=' + ctCollarType;
	}
	if(ctSeasonNumber){
		piUrl += '&ctSeasonNumber=' + ctSeasonNumber;
	}
	if(reference){
		piUrl += '&reference=' + reference;
	}
    if (!piWindow) {
        piWindow = new Ext.Window({
            title: message.get('message.combo.pleaseselect'),
            layout: 'fit',
            width: 960,
            height: 605,
            closeAction: 'hide',
            plain: true,
            modal: true,
            items: [{
                id: 'buttonPanel',
                region: 'center',
                bodyStyle: {
                    background: '#ffffff',
                    padding: '7px'
                },
                html: '<div id="piDiv"></div>'
            }]
        });
    }
    piWindow.show();
    
    if (piGrid) {
		piStore.proxy = new Ext.data.HttpProxy({
				url : piUrl
			});
		piStore.reload();
        return;
    }
    
    piStore =  new Ext.data.Store({
        url: piUrl,
        reader: new Ext.data.XmlReader({
            record: 'item',
            id: 'id',
            totalRecords: 'itemTotal'
        }, [ 
        'index', 'id', 'ctProductFamily','ctProductIdentificationStyle', 'biMeasureSpecificationId','biMeasureSpecificationName',
		'ctMachineType', 'type', 'orderNumber','referenceAs',
		 'yarnNumber', 'dhlNumber', 'ctDesignType',
		 'style', 'customerLinkman', 'model', 
		 'ctSeasonNumber', 'createDate', 'reference',
		 'ctVersion', 'patronageNumer', 
		 'ctCollarType',
		 'frontReference',
		 'frontPhotoName', 
		 'backReference', 
		 'backPhotoName',
		 'sleevesReference',
		 'sleevesPhotoName',  
		 'bottomThrumReference',
		 'bottomThrumPhotoName',  
		 'sleevesThrumReference',
		 'sleevesThrumPhotoName', 
		 'necklineThrumReference',
		 'necklineThrumPhotoName',
		 'needle',
		 'mainComposition',
		 'equipment',
		 'factoryName',
		 'weight', 'comment', 'frontPhotoName','backPhotoName','otherPhotoName',
		 'sketch1Name','sketch2Name','sketch3Name','sketch4Name', 'modifyDate', 
		 'isSimilary', 'isNewfashioned', 'isDifficulty', 'densityColumms1','densityRows1', 'densityColumms2','densityRows2', 'densityColumms3','densityRows3', 'densityColumms4','densityRows4', 'densityColumms5','densityRows5', 'densityColumms6','densityRows6',
		 'dhlNumber', {name: 'biFranceCustomer.name', mapping: 'customerName'},
		 {name: 'biFranceCustomer.department', mapping: 'customerDepartment'},'isTagged','isYarned', 'isOrdered', 'isButtoned', 'isZipped', 'isAo','isMeasurement','jauge']),
        
        remoteSort: true
    });
    
    piStore.setDefaultSort('id', 'desc');
    
	var piFilters = new Ext.grid.GridFilters({
					  filters:[
						{type: 'list',  dataIndex: 'ctSeasonNumber', options: ctSeasonNumberXmlLoader.getCtArray() },
						{type: 'list',  dataIndex: 'ctDesignType', options: ctDesignTypeXmlLoader.getCtArray() },
						{type: 'list',  dataIndex: 'ctProductIdentificationStyle', options: ctProductIdentificationStyleXmlLoader.getCtArray() },
						{type: 'string',  dataIndex: 'biFranceCustomer.name'},
						{type: 'string',  dataIndex: 'biFranceCustomer.department'},
						{type: 'string',  dataIndex: 'model'},
						{type: 'string',  dataIndex: 'reference'},
						{type: 'string',  dataIndex: 'style'},
						{type: 'date',  dataIndex: 'createDate'},
						{type: 'date',  dataIndex: 'modifyDate'},
						{type: 'list',  dataIndex: 'ctVersion',options: ctVersionXmlLoader.getCtArray()},
						{type: 'string',  dataIndex: 'patronageNumer'}
				]});
	
	var piExpander = new Ext.grid.RowExpander({
	        tpl : new Ext.XTemplate(
				'<br/><p><b>' + referenceMessage.get('ui.reference.weight') + '(Kg):</b> {weight}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
						'<b>' + piMessage.get('ui.productidentification.ordernumber') + ':</b> {orderNumber}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
						'<b>' + fMessage.get('ui.factory.name') + ':</b> {factoryName}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
						'<b>' + piMessage.get('ui.productidentification.set3') + ':</b> {[this.convertEqu(values.equipment)]}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
						'</p><br/>',
						'<p><img src="../../_temp/{sketch1Name}" width="150px"/> &nbsp;&nbsp;&nbsp;&nbsp;<img src="../../_temp/{sketch2Name}" width="150px"/>&nbsp;&nbsp;&nbsp;&nbsp;<img src="../../_temp/{sketch3Name}" width="150px"/>&nbsp;&nbsp;&nbsp;&nbsp;<img src="../../_temp/{sketch4Name}" width="150px"/></p><br/>',
						'<table>',
						'<tr><td width="180"><b>' + referenceMessage.get('ui.reference.front') + ':</b> {frontReference}<br/><b>' +  piMessage.get('ui.productidentification.densitycolumms') + '{densityColumms1}&nbsp;&nbsp;<b>' +  piMessage.get('ui.productidentification.densityrows') + '{densityRows1}</td><td width="180"><b>' + referenceMessage.get('ui.reference.sleevesthrum') + ':</b> {sleevesThrumReference}<br/><b>' +  piMessage.get('ui.productidentification.densitycolumms') + '{densityColumms2}&nbsp;&nbsp;<b>' +  piMessage.get('ui.productidentification.densityrows') + '{densityRows2}</td><td width="180"><b>' + referenceMessage.get('ui.reference.sleeves') + ':</b> {sleevesReference}<br/><b>' +  piMessage.get('ui.productidentification.densitycolumms') + '{densityColumms3}&nbsp;&nbsp;<b>' +  piMessage.get('ui.productidentification.densityrows') + '{densityRows3}</td></tr>',
						'<tr><td><img src="../../_temp/{frontPhotoName}" width="150px" onclick="openImageViewer(this.src);"/></td><td><img src="../../_temp/{sleevesThrumPhotoName}" width="150px" onclick="openImageViewer(this.src);"/></td><td><img src="../../_temp/{sleevesPhotoName}" width="150px" onclick="openImageViewer(this.src);"/></td></tr>',
						'<tr><td width="180"><b>' + referenceMessage.get('ui.reference.bottomthrum') + ':</b> {bottomThrumReference}<br/><b>' +  piMessage.get('ui.productidentification.densitycolumms') + '{densityColumms4}&nbsp;&nbsp;<b>' +  piMessage.get('ui.productidentification.densityrows') + '{densityRows4}</td><td width="180"><b>' + referenceMessage.get('ui.reference.back') + ':</b> {backReference}<br/><b>' +  piMessage.get('ui.productidentification.densitycolumms') + '{densityColumms5}&nbsp;&nbsp;<b>' +  piMessage.get('ui.productidentification.densityrows') + '{densityRows5}</td><td width="180"><b>' + referenceMessage.get('ui.reference.necklinethrum') + ':</b> {necklineThrumReference}<br/><b>' +  piMessage.get('ui.productidentification.densitycolumms') + '{densityColumms6}&nbsp;&nbsp;<b>' +  piMessage.get('ui.productidentification.densityrows') + '{densityRows6}</td></tr>',
						'<tr><td><img src="../../_temp/{bottomThrumPhotoName}" width="150px" onclick="openImageViewer(this.src);"/></td><td><img src="../../_temp/{backPhotoName}" width="150px" onclick="openImageViewer(this.src);"/></td><td><img src="../../_temp/{necklineThrumPhotoName}" width="150px" onclick="openImageViewer(this.src);"/></td></tr>',
						'</table>',
						'<br/><br/><p><b>' + piMessage.get('ui.productidentification.comment') + ':</b> {comment}</p><br/>', {
						     convertEqu: function(name){
						     	if(name.indexOf('equipmentother') == -1){
						     		return fMessage.get('ui.factory.' + name);
						     	}else{
						     		return fMessage.get('ui.factory.equipmentother') + name.substring(name.length - 1);
						     	}
						     }
						}
	        )
	    });
	    
	    
	 function renderSelectItem(value, p, record, rowIndex){
        //var selectReferenceCallback = function(id,reference, needle,ctMachineType, weight,front,back,
        //sleeves,bottomThrum,sleevesThrum,necklineThrum,frontPhotoName,backPhotoName,otherPhotoName){
        return String.format('<a href="javascript: locateProductIdentification({10});selectPiCallback(\'{0}\',\'{1}\',\'{2}\',\'{3}\',\'{4}\',\'{5}\',\'{6}\',\'{7}\',\'{8}\',\'{9}\');piWindow.hide();"><img src="../../images/icons/arrow_rotate_clockwise.png" title="' + message.get('message.list.select') + '" /></a>', 
								    record.data.id,
								    record.data.reference,
								    record.data['biFactory.name'],
		 							record.data.ctYarnMaterial1,
		 							record.data.ctYarnMaterial2,
		 							record.data.ctYarnMaterial3,
		 							record.data.ctYarnMaterial4,
		 							record.data.ctYarnMaterial5,
		 							record.data.ctYarnMeasure,
		 							record.data.yarnAccount,
		 							rowIndex);
    }
	    
	// create the grid
    piGrid = new Ext.grid.GridPanel({
                    title: piMessage.get('ui.productidentification.listtitle'),
                    store: piStore,
					stripeRows: true,
					plugins: [piFilters, piExpander],
                    height: 560,
                    columns: [piExpander, {
                        header: message.get('message.list.id'),
                        width: 50,
                        dataIndex: 'index',
                        sortable: false
                    },{
                        header: piMessage.get('ui.productidentification.seasonnumber'),
                        dataIndex: 'ctSeasonNumber',
                        sortable: true
                    },{
                        header: piMessage.get('ui.productidentification.designtype'),
                        dataIndex: 'ctDesignType',
                        sortable: true
                    }, {
                        header: fcMessage.get('ui.francecustomer.name'),
                        dataIndex: 'biFranceCustomer.name',
                        sortable: true
                    }, {
                        header: fcMessage.get('ui.francecustomer.department'),
                        dataIndex: 'biFranceCustomer.department',
                        sortable: true
                    },{
                        header: referenceMessage.get('ui.reference.reference'),
                        dataIndex: 'reference',
                        sortable: true
                    },{
                        header: piMessage.get('ui.productidentification.style'),
                        dataIndex: 'ctCollarType',
                        sortable: true
                    },{
                        header: '',
                        dataIndex: 'ctProductIdentificationStyle',
                        sortable: true
                    },{
                        header: piMessage.get('ui.productidentification.chartversion'),
                        dataIndex: 'ctVersion',
                        sortable: true
                    },{
                        header: yarnMessage.get('ui.yarn.composition'),
                        dataIndex: 'mainComposition',
                        sortable: true
                    },{
                        header: fMessage.get('ui.factory.jauge'),
                        dataIndex: 'jauge',
                        sortable: true
                    },{
			            header: message.get('message.list.select'),
			            width: 60,
			            dataIndex: 'id',
			            sortable: false,
			            renderer: renderSelectItem
			        }],
                    viewConfig: {
                        forceFit: true
                    },
                    loadMask: true,
                    renderTo: 'piDiv',
                    bbar: new Ext.PagingToolbar({
                        pageSize: 20,
                        store: piStore,
                        displayInfo: true
                    })
                });
    
    var startPage = getPrarmeterValue(window.location, 'startPage');
    var start;
    if (startPage == null || startPage == '') {
        start = 0;
    }
    else {
        start = (startPage - 1) * 20;
    }
    piStore.load({
        params: {
            start: start,
            limit: 20
        }
    });
}

